import { useState } from 'react';

type Message = { role: 'user' | 'assistant'; content: string };

export default function Consultation() {
  const [symptom, setSymptom] = useState('');
  const [messages, setMessages] = useState<Message[]>([
    { role: 'assistant', content: '请简要描述您的不适与持续时间，我将为您进行初步判断。' },
  ]);
  const [loading, setLoading] = useState(false);

  async function send() {
    if (!symptom.trim()) return;
    const input = symptom.trim();
    setMessages((m) => [...m, { role: 'user', content: input }]);
    setSymptom('');
    setLoading(true);
    try {
      const resp = await fetch('/api/chat/doubao', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          messages: [
            { role: 'system', content: '你是一名合规的医疗助手，仅提供通用健康建议，不做诊断或处方。' },
            ...messages.map((m) => ({ role: m.role, content: m.content })),
            { role: 'user', content: input }
          ],
          model: 'doubao-1-5-thinking-pro-250415'
        })
      });
      if (!resp.ok) throw new Error(await resp.text());
      const data = await resp.json();
      const reply = data?.reply || '抱歉，暂时无法获取建议，请稍后重试。';
      setMessages((m) => [...m, { role: 'assistant', content: reply }]);
    } catch {
      // fallback to local mock
      const lower = input.toLowerCase();
      let reply = '已记录您的症状，我会综合评估给出建议。';
      if (lower.includes('发烧') || lower.includes('发热')) reply = '考虑上呼吸道感染或炎症，建议多饮水、物理降温，必要时就诊内科。';
      if (lower.includes('咳') || lower.includes('咳嗽')) reply = '若伴有黄痰或持续>1周，建议呼吸内科就诊，注意休息与补水。';
      if (lower.includes('腹痛') || lower.includes('肚子')) reply = '留意是否与饮食相关，如剧烈持续或伴发热、呕吐，尽快消化内科就诊。';
      setMessages((m) => [...m, { role: 'assistant', content: reply }]);
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="flex h-full flex-col">
      <div className="rounded-2xl bg-white p-4 shadow-sm flex-1 overflow-auto space-y-3">
        {messages.map((m, i) => (
          <div key={i} className={`flex ${m.role === 'user' ? 'justify-end' : 'justify-start'}`}>
            <div className={`max-w-[80%] rounded-2xl px-3 py-2 text-sm ${m.role === 'user' ? 'bg-brand-600 text-white' : 'bg-gray-100 text-gray-800'}`}>
              {m.content}
            </div>
          </div>
        ))}
      </div>

      <div className="mt-3 flex items-center gap-2">
        <input value={symptom} onChange={(e) => setSymptom(e.target.value)} placeholder="描述症状，如：发热咳嗽三天..." className="flex-1 rounded-xl border bg-white px-3 py-3 text-sm outline-none" />
        <button onClick={send} disabled={loading} className={`rounded-xl px-4 py-3 text-white ${loading ? 'bg-gray-400' : 'bg-brand-600'}`}>{loading ? '请稍候' : '发送'}</button>
      </div>
    </div>
  );
}


